<template>
  <j-modal
    :title="title"
    :width="1200"
    :visible="visible"
    :confirmLoading="confirmLoading"
    switchFullscreen
    @ok="handleOk"
    @cancel="handleCancel"
    cancelText="关闭">
    
    <a-spin :spinning="confirmLoading">
      <a-form :form="form" class="compact-form">
        <a-card title="基本信息" :bordered="false" style="margin-bottom: 4px;" :bodyStyle="{padding: '4px 16px'}">
          <a-row :gutter="8">
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="订单名称">
                <a-input placeholder="请输入订单名称" v-decorator="['orderName', validatorRules.orderName ]" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="订单类型">
                <j-dict-select-tag type="list" v-decorator="['orderType', validatorRules.orderType]" :trigger-change="true" dictCode="order_type" placeholder="请选择订单类型"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="订单进度">
                <j-dict-select-tag type="list"
                                  v-decorator="['orderProgress', validatorRules.orderProgress]"
                                  :trigger-change="true"
                                  dictCode="order_progress"
                                  placeholder="请选择订单进度"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        
        <a-card title="日期信息" :bordered="false" style="margin-bottom: 4px;" :bodyStyle="{padding: '4px 16px'}">
          <a-row :gutter="8">
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="下单日期">
                <j-date placeholder="请选择下单日期" v-decorator="['orderDate', validatorRules.orderDate]" :trigger-change="true" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="交付日期">
                <j-date placeholder="选择交付日期（可选）" v-decorator="['deliveryDate', validatorRules.deliveryDate]" :trigger-change="true" style="width: 100%"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="售后截止">
                <j-date placeholder="选择售后截止日期（可选）" v-decorator="['afterSaleEndDate', validatorRules.afterSaleEndDate]" :trigger-change="true" style="width: 100%"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        
        <a-card title="金额信息" :bordered="false" style="margin-bottom: 4px;" :bodyStyle="{padding: '4px 16px'}">
          <a-row :gutter="8">
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="订单金额">
                <a-input-number style="width: 100%" placeholder="请输入订单金额"
                                v-decorator="['orderAmount', validatorRules.orderAmount ]"
                                :precision="2"
                                @change="(value) => handleOrderAmountChange(value)"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="抽成比例">
                <a-input-number style="width: 100%" placeholder="请输入抽成比例" 
                                v-decorator="['commissionRate', validatorRules.commissionRate ]" 
                                :min="0" 
                                :max="100" 
                                :step="1" 
                                :formatter="value => `${value}%`" 
                                :parser="value => value.replace('%', '')" 
                                @change="(value) => handleCommissionRateChange(value)"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="本单利润">
                <a-input-number style="width: 100%" placeholder="本单利润" v-decorator="['profit', validatorRules.profit ]" :disabled="true"/>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="程序员分成">
                <a-input-number style="width: 100%" placeholder="程序员分成金额" v-decorator="['programmerAmount', validatorRules.programmerAmount ]" :disabled="true"/>
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        
        <a-card title="联系信息" :bordered="false" style="margin-bottom: 4px;" :bodyStyle="{padding: '4px 16px'}">
          <a-row :gutter="8">
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="程序员">
                <div class="programmer-select-wrapper">
                  <a-input v-decorator="['programmerId', validatorRules.programmerId]" style="display: none" />
                  <a-input v-decorator="['programmerName', {}]" placeholder="请选择程序员" :disabled="true" style="width: calc(100% - 75px)" />
                  <a-button type="primary" style="margin-left: 5px" @click="openSelectProgrammerModal">选择</a-button>
                </div>
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="客户名称">
                <a-input placeholder="请输入客户名称" v-decorator="['customerName', validatorRules.customerName ]" />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item
                :labelCol="{span: 6}"
                :wrapperCol="{span: 18}"
                label="客户微信">
                <a-input placeholder="请输入客户微信" v-decorator="['customerWechat', validatorRules.customerWechat ]" />
              </a-form-item>
            </a-col>
          </a-row>
        </a-card>
        
        <a-card title="备注信息" :bordered="false" :bodyStyle="{padding: '4px 16px'}">
          <a-form-item
            :labelCol="{span: 2}"
            :wrapperCol="{span: 22}"
            label="订单备注">
            <a-textarea placeholder="请输入订单备注" v-decorator="['orderRemark', {}]" :rows="4" />
          </a-form-item>
        </a-card>
      </a-form>
    </a-spin>
    
    <!-- 选择程序员模态框 -->
    <select-programmer-modal ref="selectProgrammerModal" @select="handleSelectProgrammer"></select-programmer-modal>
  </j-modal>
</template>

<script>
  import { httpAction, getAction } from '@/api/manage'
  import pick from 'lodash.pick'
  import moment from "moment"
  import SelectProgrammerModal from './SelectProgrammerModal'

  export default {
    name: "BOrderInfoModal",
    components: {
      SelectProgrammerModal
    },
    data () {
      return {
        title:"操作",
        visible: false,
        model: {},
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        confirmLoading: false,
        form: this.$form.createForm(this),
        validatorRules:{
          orderName: {rules: [{ required: true, message: '请输入订单名称!' }]},
          orderType: {rules: [{ required: true, message: '请选择订单类型!' }]},
          orderDate: {rules: [{ required: true, message: '请选择下单日期!' }]},
          deliveryDate: {rules: [{ required: false, message: '请选择交付日期!' }]},
          afterSaleEndDate: {rules: [{ required: false, message: '请选择售后截止日期!' }]},
          orderAmount: {rules: [{ required: true, message: '请输入订单金额!' }]},
          commissionRate: {rules: [{ required: true, message: '请输入抽成比例!' }]},
          programmerAmount: {rules: [{ required: true, message: '程序员分成金额!' }]},
          profit: {rules: [{ required: true, message: '本单利润!' }]},
          orderProgress: {rules: [{ required: true, message: '请选择订单进度!' }]},
          programmerId: {rules: [{ required: true, message: '请选择程序员!' }]},
          customerName: {rules: [{ required: false, message: '请输入客户名称!' }]},
          customerWechat: {rules: [{ required: true, message: '请输入客户微信!' }]},
        },
        url: {
          add: "/order/bOrderInfo/add",
          edit: "/order/bOrderInfo/edit",
          getProgrammerById: "/order/bProgrammerInfo/queryById"
        },
        selectedProgrammer: null
      }
    },
    created () {
    },
    methods: {
      add () {
        this.edit({});
      },
      edit (record) {
        this.form.resetFields();
        this.model = Object.assign({}, record);
        this.visible = true;
        this.$nextTick(() => {
          // 设置表单字段值
          const formValues = pick(this.model,
            'orderName',
            'orderType',
            'orderAmount',
            'commissionRate',
            'programmerAmount',
            'profit',
            'orderProgress',
            'programmerId',
            'customerName',
            'customerWechat',
            'orderRemark'
          );
          
          // 处理日期字段
          if (this.model.orderDate) {
            formValues.orderDate = moment(this.model.orderDate);
          }
          
          if (this.model.deliveryDate) {
            formValues.deliveryDate = moment(this.model.deliveryDate);
          }
          
          if (this.model.afterSaleEndDate) {
            formValues.afterSaleEndDate = moment(this.model.afterSaleEndDate);
          }
          
          // 如果是新增记录，设置抽成比例默认值为20%
          if (!this.model.id && !formValues.commissionRate) {
            formValues.commissionRate = 20;
          }
          
          this.form.setFieldsValue(formValues);
          
          // 如果有程序员ID，获取程序员信息
          if (this.model.programmerId) {
            this.loadProgrammerInfo(this.model.programmerId);
          }
          
          // 如果有订单金额和抽成比例，计算利润和程序员分成
          if (formValues.orderAmount && formValues.commissionRate) {
            this.calculateProfit();
          }
        });
      },
      close () {
        this.$emit('close');
        this.visible = false;
      },
      calculateProfit() {
        const form = this.form;
        const orderAmount = form.getFieldValue('orderAmount');
        console.log('orderAmount',orderAmount)
        const commissionRate = form.getFieldValue('commissionRate');
        
        if (orderAmount && commissionRate !== undefined && commissionRate !== null) {
          // 确保使用数值计算
          const orderAmountNum = Number(orderAmount);
          const commissionRateNum = Number(commissionRate);
          
          // 本单利润 = 订单金额 * (抽成比例 / 100)
          const profit = parseFloat((orderAmountNum * (commissionRateNum / 100)).toFixed(2));
          
          // 程序员分成金额 = 订单金额 * (100 - 抽成比例) / 100
          const programmerAmount = parseFloat((orderAmountNum * ((100 - commissionRateNum) / 100)).toFixed(2));
          
          // 验证计算结果：profit + programmerAmount 应该等于 orderAmount
          console.log('计算结果验证：', {
            orderAmount: orderAmountNum,
            profit,
            programmerAmount,
            sum: profit + programmerAmount
          });
          
          form.setFieldsValue({
            profit: profit,
            programmerAmount: programmerAmount
          });
        }
      },
      // 处理订单金额变化
      handleOrderAmountChange(value) {
        console.log('订单金额变化:', value);
        // 直接使用传入的value进行计算
        const form = this.form;
        const commissionRate = form.getFieldValue('commissionRate');
        
        if (value && commissionRate !== undefined && commissionRate !== null) {
          // 确保使用数值计算
          const orderAmountNum = Number(value);
          const commissionRateNum = Number(commissionRate);
          
          // 本单利润 = 订单金额 * (抽成比例 / 100)
          const profit = parseFloat((orderAmountNum * (commissionRateNum / 100)).toFixed(2));
          
          // 程序员分成金额 = 订单金额 * (100 - 抽成比例) / 100
          const programmerAmount = parseFloat((orderAmountNum * ((100 - commissionRateNum) / 100)).toFixed(2));
          
          console.log('订单金额变化后计算结果：', {
            orderAmount: orderAmountNum,
            profit,
            programmerAmount,
            sum: profit + programmerAmount
          });
          
          form.setFieldsValue({
            profit: profit,
            programmerAmount: programmerAmount
          });
        }
      },
      // 处理抽成比例变化
      handleCommissionRateChange(value) {
        console.log('抽成比例变化:', value);
        // 直接使用传入的value进行计算
        const form = this.form;
        const orderAmount = form.getFieldValue('orderAmount');
        
        if (orderAmount && value !== undefined && value !== null) {
          // 确保使用数值计算
          const orderAmountNum = Number(orderAmount);
          const commissionRateNum = Number(value);
          
          // 本单利润 = 订单金额 * (抽成比例 / 100)
          const profit = parseFloat((orderAmountNum * (commissionRateNum / 100)).toFixed(2));
          
          // 程序员分成金额 = 订单金额 * (100 - 抽成比例) / 100
          const programmerAmount = parseFloat((orderAmountNum * ((100 - commissionRateNum) / 100)).toFixed(2));
          
          console.log('抽成比例变化后计算结果：', {
            orderAmount: orderAmountNum,
            commissionRate: commissionRateNum,
            profit,
            programmerAmount,
            sum: profit + programmerAmount
          });
          
          form.setFieldsValue({
            profit: profit,
            programmerAmount: programmerAmount
          });
        }
      },
      // 打开选择程序员模态框
      openSelectProgrammerModal() {
        this.$refs.selectProgrammerModal.show();
      },
      // 处理选择程序员
      handleSelectProgrammer(programmer) {
        this.selectedProgrammer = programmer;
        this.form.setFieldsValue({
          programmerId: programmer.id,
          programmerName: programmer.realName
        });
      },
      // 加载程序员信息
      loadProgrammerInfo(programmerId) {
        getAction(this.url.getProgrammerById, {id: programmerId}).then(res => {
          if (res.success) {
            this.selectedProgrammer = res.result;
            this.form.setFieldsValue({
              programmerName: res.result.realName
            });
          }
        });
      },
      handleOk () {
        const that = this;
        // 触发表单验证
        this.form.validateFields((err, values) => {
          if (!err) {
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
              method = 'put';
            }
            let formData = Object.assign({}, this.model, values);
            
            // 时间格式化
            if (formData.orderDate && formData.orderDate._isAMomentObject) {
              formData.orderDate = formData.orderDate.format('YYYY-MM-DD');
            }
            
            if (formData.deliveryDate && formData.deliveryDate._isAMomentObject) {
              formData.deliveryDate = formData.deliveryDate.format('YYYY-MM-DD');
            }
            
            if (formData.afterSaleEndDate && formData.afterSaleEndDate._isAMomentObject) {
              formData.afterSaleEndDate = formData.afterSaleEndDate.format('YYYY-MM-DD');
            }
            
            console.log('提交的表单数据:', formData);
            httpAction(httpurl, formData, method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
              that.close();
            })
          }
        })
      },
      handleCancel () {
        this.close()
      },
    }
  }
</script>

<style scoped>
  .programmer-select-wrapper {
    display: flex;
    align-items: center;
  }
  
  /* 紧凑型表单样式 */
  .compact-form /deep/ .ant-form-item {
    margin-bottom: 4px;
  }
  
  .compact-form /deep/ .ant-card-head {
    min-height: 36px;
    padding: 0 16px;
  }
  
  .compact-form /deep/ .ant-card-head-title {
    padding: 8px 0;
    font-size: 14px;
  }
</style> 